import { defineStore} from 'pinia'
import api from '../api/http'
import { formatLoginData, routerToTree, menuDataToTree} from '../util/dataToTree'
import { router} from '../router'
// import {RouteRecordName} from 'vue-router'
interface StateType {
    menuList: any,
    permissionList: any,
    userRight:any
}
type ActionType = { 
    FETCH_PERMISSION(): Promise<void>
    clearMenu():void
    clearPermission():void
 }
export interface UserInfo {
        id:number,
        pid:number,
        path:string,
        link:string,
        name:string,
        right:string[],
        title:string,
        children?:UserInfo[]
}    
interface AuthData {
    authData:UserInfo[]
}
export const useControlStore = defineStore<string, StateType, {}, ActionType>('loginController', {
    state: () => {
        return {
            menuList: '',
            permissionList: '',
            userRight:""
        }
    },
    actions: {
        async FETCH_PERMISSION() {
            try{
                const res:AuthData = await api.getMenu()
                const data = formatLoginData(res.authData)
                
                //  路由结构
                const dynamicRouter = routerToTree(data)
                //  菜单数据结构

                const menuList = menuDataToTree(data)
                  this.menuList = menuList   

                //动态添加路由
                  const initialRoutes  = router.options.routes;
                  const route = initialRoutes.find(item=>item.name==='layout') as any
                  dynamicRouter.forEach(item=>{
                    router.addRoute(route.name,item)
                  })
                  
                  //下面这中 
                 //   router.addRoute(route?.name,...dynamicRouter)
                 // const route = staticRouter.find(item => item.name === 'layout')
                 // route?.children?.push(...dynamicRouter)
                 // staticRouter.forEach(item=>{
                 //     router.addRoute(item)
                 // })
                 //路由都还没有，有数据有啥用
                this.permissionList = [initialRoutes[0],dynamicRouter[0]]

                  //用户按钮级别权限，很多做法，根据后台啥事返回的 ,我这已登录就有了，你也可以保存route 的meta里 每个页面都可以拿到
                this.userRight =res.authData[0].right
            }catch(err){
                console.log(err)

            }
        },
        clearMenu(){
            this.menuList = ''
        },
        clearPermission(){
            this.permissionList=''
        }
    }
})

